package cn.ronghuanet.auth.controller;

import cn.ronghuanet.auth.dto.LoginDTO;
import cn.ronghuanet.auth.service.ILoginService;
import cn.ronghuanet.basic.util.AjaxResult;
import cn.ronghuanet.basic.util.BasicMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private ILoginService loginService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginDTO loginDTO){
        try {
            Map<String,Object> map = loginService.login(loginDTO);
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("登录失败!"+e.getMessage());
        }
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            // 从loginMap中删除登录用户信息
            BasicMap.loginMap.remove(token);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("退出登录失败!"+e.getMessage());
        }
    }
}
